package com.studychen.appfxcp.commom.components;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

import java.util.ArrayList;
import java.util.List;

public class CpMenuItem extends Button {

    private EventHandler<ActionEvent> onclick;

    private static List<CpMenuItem> menuItems = new ArrayList<>();

    private static Font customFont = Font.loadFont(CpMenuItem.class.getResourceAsStream("/com/studychen/appfxcp/commom/fonts/iconfont.ttf"), 20.0);

    public CpMenuItem(String text, CustomIconEnum icon) {
        HBox b = new HBox();
        b.getStyleClass().add("menu-group");
        b.setAlignment(Pos.CENTER);
        b.setSpacing(5);
        Text l0 = null;
        if(icon != null){
            l0 = new Text();
            l0.setText(String.valueOf(icon.unicode));
            l0.setFont(customFont);
            l0.getStyleClass().addAll("menu-item-icon");
        }

        Label l = new Label(text);
        l.getStyleClass().addAll( "menu-item-label");
        if(l0 != null){
            b.getChildren().add(l0);
        }
        b.getChildren().addAll( l);

        this.getStyleClass().add("menu-item");
        this.setGraphic(b);
        menuItems.add(this);
        var self = this;
        this.setOnAction((e) -> {
            self.getStyleClass().add("menu-item-click");
            menuItems.forEach(it -> {
                if(it != self){
                    it.getStyleClass().remove("menu-item-click");
                }
            });
            if(onclick != null){
                onclick.handle(e);
            }
        });
    }

    public void setOnClick(EventHandler<ActionEvent> onclick){
        this.onclick = onclick;
    }

    public void click(){
        this.fire();
    }
}
